package com.sinocare.project.common.config;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sinocare.project.common.util.JwtTokenUtil;
import org.apache.shiro.spring.config.ShiroConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(ShiroConfiguration.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.info(token);
        Map<String, Object> map = new HashMap<>();
        try {
//验签token有效性
            JwtTokenUtil.verify(token);
            return true;	//token验签通过，放行，可以调用controller接口
        } catch(TokenExpiredException e){
            map.put("msg", "Token已过期！！！");
            map.put("state", false);
        } catch(SignatureVerificationException e){
            map.put("msg", "签名错误！！！");
            map.put("state", false);
        } catch(AlgorithmMismatchException e){
            map.put("msg", "加密算法不匹配！！！");
            map.put("state", false);
        } catch(Exception e){
            map.put("msg", "无效token！！！");
            map.put("state", false);
        }
//jackson转换的对象
        String json = new ObjectMapper().writeValueAsString(map);
//设置响应类型
        response.setContentType("application/json;charset=UTF-8");
//向前端响应json
//        response.getWriter().println(json);
        log.info(json);
        return false;
    }
}
